package com.yanyeori.framework.core.context;

import com.yanyeori.framework.core.constant.BaseWebCodeEnum;
import com.yanyeori.framework.core.constant.ChannelEnum;
import com.yanyeori.framework.core.exception.NoUserContextException;
import lombok.*;

import java.io.Serializable;

/**
 * 登陆用户上下文信息
 *
 * @author chenkuan 2020/11/24
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class UserContext implements Serializable {
    private static final long serialVersionUID = 1L;

    //用户id
    private String userId;
    //用户名
    private String username;
    //昵称
    private String nickname;
    //登录ip
    private String loginIp;
    //登录渠道
    private ChannelEnum channel;

    public static UserContext get() {
        return ContextHolder.USER_CONTEXT_HOLDER.get();
    }

    public static UserContext getRequired() {
        UserContext userContext = get();
        if (userContext == null) {
            throw new NoUserContextException(BaseWebCodeEnum.NO_USER_CONTEXT.code(), BaseWebCodeEnum.NO_USER_CONTEXT.msg());
        }
        return userContext;
    }

    public static String username() {
        UserContext userContext = get();
        if (userContext == null) return null;
        return userContext.getUsername();
    }

    public static void set(UserContext context) {
        ContextHolder.USER_CONTEXT_HOLDER.set(context);
    }

    public static void clear() {
        ContextHolder.USER_CONTEXT_HOLDER.remove();
    }
}
